//
//  TopicDiscussList_tv_cell.m
//  ainkjj
//
//  Created by MAX on 2020/5/8.
//  Copyright © 2020 zhiyiLiu. All rights reserved.
//

#import "TopicDiscussList_tv_cell.h"

#import "TopicDiscussListSondiscusslist_tv_cell.h"

#import "Tiezi_pinglun_vc.h"

#import "Tiezi_pinglun_erji_vc.h"

#import "StringCalculateManager.h"

static UIEdgeInsets const kInsets_dis = {15, 16, 15, 16};
static CGSize const kAvatarSize = {38, 38};
static CGFloat const  kAvatarMarginRight = 10;
static CGFloat const  kAvatarMarginBottom = 12;
static CGFloat const  kContentMarginBotom = 12;

static NSString * const kCellIdentifier = @"TopicDiscussListSondiscusslist_tv_cell";


@interface TopicDiscussList_tv_cell()<QMUITableViewDelegate, QMUITableViewDataSource>
@property (nonatomic, strong)NSArray *dataArr;

@end

@implementation TopicDiscussList_tv_cell

- (void)didInitializeWithStyle:(UITableViewCellStyle)style {
    [super didInitializeWithStyle:style];
    [self setSelectionStyle:UITableViewCellSelectionStyleNone];
    //    self.contentView.backgroundColor = UIColor.groupTableViewBackgroundColor;
    //    _bgV = [UIView new];
    //    [self.contentView addSubview:_bgV];
    //    _bgV.backgroundColor = UIColor.whiteColor;
    //    _bgV.layer.masksToBounds = YES;
    //    _bgV.layer.cornerRadius = 5;
    
    _avatarImageView = [[UIImageView alloc] init];
    [self.contentView addSubview:self.avatarImageView];
    _avatarImageView.layer.masksToBounds = YES;
    _avatarImageView.layer.cornerRadius = kAvatarSize.height * 0.5;
    _nameLabel = [[UILabel alloc] qmui_initWithFont:UIFontBoldMake(16) textColor:rgb(17,17,17)];
    [self.contentView addSubview:self.nameLabel];
    
    
    _timeLabel = [[UILabel alloc] qmui_initWithFont:UIFontMake(15) textColor:UIColor.qd_descriptionTextColor];
    [self.contentView addSubview:self.timeLabel];
    
    _contentLabel = [[UILabel alloc] qmui_initWithFont:UIFontMake(17) textColor:UIColor.qd_mainTextColor];
    self.contentLabel.numberOfLines = 0;
    [self.contentView addSubview:self.contentLabel];
    
    
    _btn1 = [QMUIButton new];
    [self.contentView addSubview:_btn1];
    [_btn1 addTarget:self action:@selector(dianzan_action:) forControlEvents:UIControlEventTouchUpInside];
    _btn2 = [QMUIButton new];
    [self.contentView addSubview:_btn2];
    [_btn2 addTarget:self action:@selector(yiji_pinglun:) forControlEvents:UIControlEventTouchUpInside];
    [_btn1 setTitleColor:rgb(244,110,23) forState:UIControlStateSelected];
    
    [_btn1 setTitleColor:rgb(153,153,153) forState:UIControlStateNormal];
    [_btn2 setTitleColor:rgb(153,153,153) forState:UIControlStateNormal];
    
    
    self.btnArr = @[_btn1, _btn2];
    NSArray *imgs = @[@"praise_icon", @"comment_icon"];
    for ( NSUInteger i = 0; i < self.btnArr.count ; i++) {
        QMUIButton *b = self.btnArr[i];
        //        b.tintColorAdjustsTitleAndImage = UIColor.qd_tintColor;
        b.imagePosition = QMUIButtonImagePositionLeft;
        b.spacingBetweenImageAndTitle = 8;
        [b setImage:UIImageMake(imgs[i]) forState:UIControlStateNormal];
        b.titleLabel.font = UIFontMake(16);
        //        b.qmui_borderPosition = QMUIViewBorderPositionTop | QMUIViewBorderPositionBottom;
        if (i == 0) {
            [b setImage:UIImageMake(@"praise_selected_icon") forState:UIControlStateSelected];
        }
    }
    _tableView = [[QMUITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    _tableView.qmui_borderColor = TableViewSeparatorColor;
    _tableView.qmui_borderPosition = QMUIViewBorderPositionTop ;
    _tableView.scrollEnabled = NO;
    [_tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    //    _tableView.tableFooterView = UIView.new;
//    _tableView.backgroundColor = UIColor.grayColor;
    [self.contentView addSubview:_tableView];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [_tableView registerNib:[UINib nibWithNibName:@"TopicDiscussListSondiscusslist_tv_cell" bundle:nil] forCellReuseIdentifier:@"TopicDiscussListSondiscusslist_tv_cell"];
    [_tableView setContentInsetAdjustmentBehavior:UIScrollViewContentInsetAdjustmentNever];

        
//    self.contentView.backgroundColor = UIColor.redColor;
//    _tableView.backgroundColor = UIColor.yellowColor;
   
}



- (NSAttributedString *)attributeStringWithString:(NSString *)textString lineHeight:(CGFloat)lineHeight {
    if (textString.qmui_trim.length <= 0) return nil;
    NSAttributedString *attriString = [[NSAttributedString alloc] initWithString:textString attributes:@{NSParagraphStyleAttributeName:[NSMutableParagraphStyle qmui_paragraphStyleWithLineHeight:lineHeight lineBreakMode:NSLineBreakByCharWrapping textAlignment:NSTextAlignmentLeft]}];
    return attriString;
}

- (CGSize)sizeThatFits:(CGSize)size {

    CGSize resultSize = CGSizeMake(size.width, 0);
    CGFloat contentLabelWidth = ScreenWidth - UIEdgeInsetsGetHorizontalValue(kInsets_dis) - kAvatarSize.width - 10;

    CGFloat resultHeight = UIEdgeInsetsGetVerticalValue(kInsets_dis) + CGRectGetHeight(self.avatarImageView.bounds) + kAvatarMarginBottom;
    
    if (self.contentLabel.text.length > 0) {
        CGSize contentSize = [self.contentLabel sizeThatFits:CGSizeMake(contentLabelWidth, CGFLOAT_MAX) ];
        // 法二
//        CGSize contentSize =  [self.contentLabel.text boundingRectFastWithMaxWidth:contentLabelWidth withFont:self.contentLabel.font].size;
//        DLog(@"size:%@",  NSStringFromCGSize(contentSize));

        resultHeight = resultHeight +  (contentSize.height + kContentMarginBotom);
    }
    
    
    // 按钮布局依据
    resultHeight += 40;
    

    
    if (self.model.sonDiscussList.count > 0){
        
        resultHeight = resultHeight +  [self suan_ziTv] ;
        
    }
   
    
    
 
    
    resultSize.height = resultHeight ;
    //    DLog(@"%@ 的 cell 的 sizeThatFits: 被调用（说明这个 cell 的高度重新计算了一遍）", self.nameLabel.text);
    return resultSize;
}

- (void)layoutSubviews {
    [super layoutSubviews];

    
    CGFloat contentLabelWidth = ScreenWidth - UIEdgeInsetsGetHorizontalValue(kInsets_dis) - kAvatarSize.width - 10;
    self.avatarImageView.frame = CGRectMake(kInsets_dis.left, kInsets_dis.top, kAvatarSize.width, kAvatarSize.height);
    if (self.nameLabel.text.length > 0) {
        CGFloat nameLabelWidth = contentLabelWidth;
        //        nameLabelWidth = contentLabelWidth - CGRectGetWidth(self.avatarImageView.bounds) - kAvatarMarginRight - 44;
        
        CGSize nameSize = [self.nameLabel sizeThatFits:CGSizeMake(nameLabelWidth, CGFLOAT_MAX)];
        self.nameLabel.frame = CGRectFlatMake(CGRectGetMaxX(self.avatarImageView.frame) + kAvatarMarginRight, CGRectGetMinY(self.avatarImageView.frame), nameLabelWidth, nameSize.height);
    }
    
    
    if (self.contentLabel.text.length > 0) {
        CGSize contentSize = [self.contentLabel sizeThatFits:CGSizeMake(contentLabelWidth, CGFLOAT_MAX)];
        // 法二
//        CGSize contentSize =  [self.contentLabel.text boundingRectFastWithMaxWidth:contentLabelWidth withFont:self.contentLabel.font].size;

        self.contentLabel.frame = CGRectFlatMake(CGRectGetMinX(self.nameLabel.frame), CGRectGetMaxY(self.nameLabel.frame) + kAvatarMarginBottom, contentLabelWidth, contentSize.height);
//        DLog(@"%@ size:%@", NSStringFromCGRect(self.contentLabel.frame),  NSStringFromCGSize(contentSize));
        
    }
    
    if (self.timeLabel.text.length > 0) {
        CGSize timeSize = [self.timeLabel sizeThatFits:CGSizeMake(contentLabelWidth, CGFLOAT_MAX)];
        self.timeLabel.frame = CGRectFlatMake(CGRectGetMinX(self.nameLabel.frame), CGRectGetMaxY(self.contentLabel.frame) + kContentMarginBotom, timeSize.width, timeSize.height);
    }
    
    // 按钮布局依据
    CGFloat btnY = CGRectGetMaxY(self.contentLabel.frame);
    CGFloat btnW = 64;
    for (NSInteger i = 0; i < self.btnArr.count; i++) {
        QMUIButton *b = self.btnArr[i];
        b.frame = CGRectMake( ScreenWidth - (kInsets_dis.right + (self.btnArr.count - i) * btnW), btnY, btnW, 40);
    }
    
  
    
    
    
    
    if (self.model.sonDiscussList.count > 0){
        self.tableView.frame = CGRectMake(0, btnY + 40, self.contentView.frame.size.width, [self suan_ziTv] );
        
    }else{
        self.tableView.frame = CGRectZero;
    }
    
    
}
- (CGFloat)suan_ziTv{
    CGFloat sonLbH = 0;
    for (TopicDiscussListSondiscusslist *m in self.dataArr) {
        CGFloat w = ScreenWidth - 64 - 25 - kAvatarMarginRight - kInsets_dis.right;
        //            DLog(@"理论 contentW:%f", w);
        sonLbH += [Anktool boundingRectWithSize:CGSizeMake(w, CGFLOAT_MAX) font:self.contentLabel.font text:m.content numberOfLines:0].height;
        sonLbH += (UIEdgeInsetsGetVerticalValue(kInsets_dis) + kAvatarSize.height + kAvatarMarginBottom + kContentMarginBotom );
        
    }
    if (self.model.sonDiscussList.count > 2) {
        sonLbH += 44;
    }
    
    return sonLbH ;
}
- (void)setModel:(TopicDiscussListData *)model{
    _model = model;
    
    [self.avatarImageView sd_setImageWithURL:[NSURL URLWithString:model.discussAvatarUrl] placeholderImage:UIImageMake(@"mine_head_icon")];
    self.contentLabel.text = model.content;
    self.timeLabel.text = model.discussTime;
    
    
    
    // 按钮赋值
    [self.btn1 setTitle:@(model.praiseNum).stringValue forState:UIControlStateNormal];
    
    if (model.praiseStatus == 1) {
        self.btn1.selected = NO;
    }else{
        self.btn1.selected = YES;
    }
    
    
    [self.btn2 setTitle:@(model.discussNum).stringValue forState:UIControlStateNormal];
    
    self.nameLabel.text = model.discussNikeName;
    if (model.byDiscussNikeName.length > 0) {
         self.nameLabel.text = [NSString stringWithFormat:@"%@ ▷ %@", model.discussNikeName, model.byDiscussNikeName];//▶→›＞→
    }
   

    if (model.sonDiscussList.count > 0) {
        
        
        NSInteger count = MIN(2, model.sonDiscussList.count);
        NSIndexSet *idxSet = [[NSIndexSet alloc] initWithIndexesInRange:NSMakeRange(0, count)];
        self.dataArr = [model.sonDiscussList objectsAtIndexes:idxSet];
        
    }else{
        self.dataArr = @[];
    }
    
    [self.tableView reloadData];
    
 
    
}
- (void)yiji_pinglun:(QMUIButton *)sender{
    Tiezi_pinglun_vc *vc = (Tiezi_pinglun_vc *)[Anktool viewControllerForView:self];
    vc.huifuId = self.model.ID;
    vc.beihuifuren_lb.text = [NSString stringWithFormat:@"评论给%@",self.model.discussNikeName];
    [vc.textView becomeFirstResponder];
    
}
- (void)dianzan_action:(QMUIButton *)sender{
    sender.userInteractionEnabled = NO;
    
    NSString *url = sender.isSelected == YES ? @"java/app/topic/repealTopicLike" : @"java/app/topic/topicLike";
    
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setObject:app_code forKey:@"appCode"];
    [dict setObject:AuthSignin_model.sharedInstance.data.token forKey:@"token"];
    [dict setObject:@(self.model.topicId).stringValue forKey:@"topicId"];
    [dict setObject:@(self.model.ID).stringValue forKey:@"discussId"];
    
    //sender.userInteractionEnabled = NO;
    
    
    [PPHTTPRequest req:url parameters:dict success:^(id response) {
        NSString *error_code = [NSString stringWithFormat:@"%@", response[@"error_code"]];
        if ([error_code isEqualToString:@"0"]) {
            
            
            if (sender.selected) {
                self.model.praiseNum -=1;
            }else{
                self.model.praiseNum +=1;
            }
            sender.selected =  !sender.isSelected ;
            
            [self.btn1 setTitle:@(self.model.praiseNum).stringValue forState:UIControlStateNormal];
        }
        else{
            
            
            [QMUITips showError:response[@"error_msg"]];
            
        }
        sender.userInteractionEnabled = YES;
    } failure:^(NSError *error) {
        [QMUITips showError:[error localizedDescription] ];
        sender.userInteractionEnabled = YES;
    }];
}


- (id<NSCopying>)cachedKeyAtIndexPath:(NSIndexPath *)indexPath {
    
    
    TopicDiscussListSondiscusslist *model = self.dataArr[indexPath.row];
    NSString *cacheKey = @"";
    cacheKey = [NSString stringWithFormat:@"%ld_%ld",self.model.ID,  model.ID];
    
    return cacheKey;
    
}


#pragma mark - <QMUITableViewDelegate, QMUITableViewDataSource>

- (UITableViewCell *)qmui_tableView:(UITableView *)tableView cellWithIdentifier:(NSString *)identifier {
    if ([identifier isEqualToString:kCellIdentifier]) {
        TopicDiscussListSondiscusslist_tv_cell *cell = (TopicDiscussListSondiscusslist_tv_cell *)[tableView dequeueReusableCellWithIdentifier:identifier];
        if (!cell) {
            cell = [[TopicDiscussListSondiscusslist_tv_cell alloc] initForTableView:tableView withReuseIdentifier:identifier];
        }
        cell.separatorInset = UIEdgeInsetsZero;
        return cell;
    }
    
    
    return nil;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return self.dataArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    QMUITableViewCell *common_cell;
    
    TopicDiscussListSondiscusslist *model = self.dataArr[indexPath.row];
    
    TopicDiscussListSondiscusslist_tv_cell *cell = (TopicDiscussListSondiscusslist_tv_cell *)[self qmui_tableView:tableView cellWithIdentifier:kCellIdentifier];
    
    [cell updateCellAppearanceWithIndexPath:indexPath];
    cell.model = model;
    common_cell = cell;
//    cell.idxPath = indexPath;
//    __weak __typeof(self) weakSelf = self;
//    cell.blk = ^(NSIndexPath * _Nonnull idxPath) {

//    };
    
    return common_cell;
}



- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    id<NSCopying> cachedKey = [self cachedKeyAtIndexPath:indexPath];
    TopicDiscussListSondiscusslist *model = self.dataArr[indexPath.row];
    
    CGFloat cellH = 60;
    cellH = [tableView qmui_heightForCellWithIdentifier:kCellIdentifier cacheByKey:cachedKey configuration:^(TopicDiscussListSondiscusslist_tv_cell *cell) {
        [cell updateCellAppearanceWithIndexPath:indexPath];
        cell.model = model;
    }];
    
    // DLog(@"cachedKey:%@ height:%f",cachedKey, h);
    return cellH;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0.1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
        if ( self.model.sonDiscussList.count > 2 ){
            return 44;
         }
    return 0.1;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    if ( self.model.sonDiscussList.count > 2){
        
        
           UIButton *chakan_btn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 44)];
        chakan_btn.qmui_borderPosition = QMUIViewBorderPositionTop;
        
        chakan_btn.qmui_borderColor = TableViewSeparatorColor;
            //        _chakan_btn.backgroundColor = UIColor.redColor;
            [chakan_btn setTitle:[NSString stringWithFormat:@"查看全部%ld条回复", self.model.sonDiscussList.count] forState:UIControlStateNormal];
        chakan_btn.titleLabel.font = UIFontMake(17);
        [chakan_btn setTitleColor:rgb(91,132,227) forState:UIControlStateNormal];
        [chakan_btn addTarget:self action:@selector(chankan_erji_pinglun:) forControlEvents:UIControlEventTouchUpInside];
        return chakan_btn;
        
    }
    return nil;
}
- (void)chankan_erji_pinglun:(UIButton *)sender{
    
    Tiezi_pinglun_vc *vc = (Tiezi_pinglun_vc *)[Anktool viewControllerForView:self];
    Tiezi_pinglun_erji_vc *erji_vc= [[Tiezi_pinglun_erji_vc alloc]init];
    erji_vc.typeId = vc.typeId;
    erji_vc.yiji_pinglun_model = self.model;
    vc.hidesBottomBarWhenPushed = YES;
    
    [vc.navigationController pushViewController:erji_vc animated:YES];
}
@end
